package com.example.campuslink.commen.db.invitation

import android.content.Context
import androidx.room.Database
import androidx.room.Room
import androidx.room.RoomDatabase
import androidx.room.TypeConverters
import androidx.room.migration.Migration
import androidx.sqlite.db.SupportSQLiteDatabase
import com.example.campuslink.commen.db.ListListCommentTableConverter
import com.example.campuslink.commen.db.UserInfoDataConverter
import com.example.campuslink.commen.db.userNumber.ChildrenDataConverter
import com.example.campuslink.commen.db.userNumber.ListCommendInfoConverters
import db.ListStringConverter

@Database(entities = [InvitationTable::class], version = 6, exportSchema = true)
@TypeConverters(
    ListStringConverter::class,
    ListCommendInfoConverters::class,
    UserInfoDataConverter::class,
    ChildrenDataConverter::class
)
abstract class InvitationData : RoomDatabase() {
    abstract fun invitationDao(): InvitationDao

    val MIGRATION_1_2 = object : Migration(1, 2) {
        override fun migrate(database: SupportSQLiteDatabase) {
            database.execSQL("ALTER TABLE invitation_table ADD COLUMN invitationType TEXT")
        }
    }

    val MIGRATION_2_3 = object : Migration(2, 3) {
        override fun migrate(database: SupportSQLiteDatabase) {
            database.execSQL("ALTER TABLE invitation_table ADD COLUMN userInfoTable TEXT")
        }
    }

    val MIGRATION_3_4 = object : Migration(3, 4) {
        override fun migrate(database: SupportSQLiteDatabase) {
            database.execSQL("ALTER TABLE invitation_table UPDATE COLUMN invitationComment TEXT")
        }
    }

    val MIGRATION_4_5 = object : Migration(4, 5) {
        override fun migrate(database: SupportSQLiteDatabase) {
            database.execSQL("ALTER TABLE invitation_table Delete COLUMN invitationComment TEXT")
            database.execSQL("ALTER TABLE invitation_table add COLUMN invitationParentCommend TEXT")
            database.execSQL("ALTER TABLE invitation_table add COLUMN invitationChildrenCommend TEXT")
        }
    }

    val MIGRATION_5_6 = object : Migration(5, 6) {
        val MIGRATION_5_6 = object : Migration(5, 6) {
            override fun migrate(database: SupportSQLiteDatabase) {
                database.execSQL("ALTER TABLE invitation_table update COLUMN invitationParentCommend TEXT")
            }
        }
    }


    companion object {
        @Volatile
        private var INSTANCE: InvitationData? = null

        fun getDatabase(context: Context): InvitationData {
            return INSTANCE ?: synchronized(this) {
                val instance = Room.databaseBuilder(
                    context.applicationContext,
                    InvitationData::class.java,
                    "invitation_dataBase"
                )
                    .fallbackToDestructiveMigration()
                    .build()
                INSTANCE = instance
                instance
            }
        }
    }
}